package tt.dz.egobus.servicemanager.util;

import org.apache.commons.lang3.math.NumberUtils;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;

import java.util.Map;

import static tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus.PARAM_ENTITY_ERROR;

/**
 * @author Anson
 * @date 17-3-14
 * @name 相关map判断
 * @since 1.0.1
 */
public final class MapGetUtils {

    /**
     * 判断是否为空
     *
     * @param param
     * @param key
     * @return
     */
    public static <K> boolean isNull(Map<K, Object> param, K key) {
        return null == getValueOrDefault(param, key, null);
    }


    /**
     * 判断不为空
     *
     * @param param
     * @param key
     * @return
     */
    public static <K> boolean isNotNull(Map<K, Object> param, K key) {
        return null != getValueOrDefault(param, key, null);
    }

    /**
     * 判断是否为数字
     *
     * @param param
     * @param key
     * @return
     */
    public static <K> boolean isDigits(Map<K, Object> param, K key) {
        String v = getValueOrDefault(param, key, "").toString();
        return NumberUtils.isDigits(v);
    }

    /**
     * 获取当前当前值
     *
     * @param param
     * @param key
     * @param defaultValue
     * @param <K>
     * @return
     */
    public static <K> Object getValueOrDefault(Map<K, Object> param, K key, Object defaultValue) {
        return param.getOrDefault(key, defaultValue);
    }

    /**
     * 获取当前当前值,并从map中删除当前的键值对
     *
     * @param param
     * @param key
     * @param defaultValue
     * @author Anson
     * @date 17-3-16
     * @name
     * @since 1.0.1
     *
     */
    public static <K> Object getAndRemveValueOrDefault(Map<K, Object> param, K key, Object defaultValue) {
        Object obj = param.remove(key);
        return obj == null ? defaultValue : obj;
    }

    /**
     * 判断是否为数字
     *
     * @param param
     * @param key
     * @return
     * @throws tt.dz.egobus.servicemanager.core.exception.BusinessException
     */
    public static <K> int getDigits(Map<K, Object> param, K key) {
        String v = getValueOrDefault(param, key, "").toString();
        if (!NumberUtils.isDigits(v)) {
            throw new BusinessException(PARAM_ENTITY_ERROR.getCodeStatus());
        }
        return NumberUtils.toInt(v);
    }

    /**
     * 判断是否为数字,并从map中删除当前的键值对
     *
     * @param param
     * @param key
     * @return
     * @throws tt.dz.egobus.servicemanager.core.exception.BusinessException
     */
    public static <K> int getAndRemoveDigits(Map<K, Object> param, K key) {
        String v = getAndRemveValueOrDefault(param, key, "").toString();
        if (!NumberUtils.isDigits(v)) {
            throw new BusinessException(PARAM_ENTITY_ERROR.getCodeStatus());
        }
        return NumberUtils.toInt(v);
    }

}
